<template>
  <div class="gtable-container">
    <div class="toolbar-container">
      <!--工具栏-->
      <div class="table-toolbar">
        <el-button-group>
          <el-button :icon="Plus" v-if="localTableOptions.showDefaultAdd" type="primary" @click="onAdd">新增</el-button>
          <slot name="toolbar"></slot>
        </el-button-group>        
      </div>  
      <!-- 搜索工具栏 -->
      <div class="table-search-toolbar">
        <el-form inline style="width: 100%;" @submit="handleSubmit">
          <el-form-item label-width="0">
            <el-input
              v-model="generalSearchKeyword"
              placeholder="请输入关键字搜索"
              style="width: 100%;"
              @keyup.enter="handleGeneralSearch"
              @keyup.enter.native="handleGeneralSearch"
              clearable
            >
              <!-- 使用 append 插槽将按钮放入输入框右侧 -->
              <template #append>
                <el-button-group class="search-button-group">
                  <el-button native-type="button" type="info" @click="handleGeneralSearch" title="检索" :icon="Search"/>
                  <el-button type="info" v-if="localTableOptions.showAdvancedSearch" @click="toggleAdvancedSearch" title="高级检索" :icon="Filter"/>
                  <el-button type="info" v-if="localTableOptions.showRefresh" @click="refreshTable" title="刷新表格" :icon="Refresh"/>
                  <el-button type="info" v-if="localTableOptions.showColumns" ref="buttonRef" v-click-outside="onClickOutside" title="列设置" :icon="Grid"/>
                  <el-button type="info" v-if="localTableOptions.showExport" :icon="Download" ref="exportButtonRef" v-click-outside="onClickOutsideExport" title="导出可见列数据到excel文件"/>
                  <el-button type="info" v-if="localTableOptions.showImport" :icon="Upload" @click="handleExcelImport" />
                  <el-popover
                    ref="popoverRef"
                    :virtual-ref="buttonRef"
                    trigger="click"
                    title="列设置"
                    virtual-triggering
                    placement="bottom"
                    :width="200"   
                  >
                    <div>
                      <div class="search-and-select">
                        <el-input v-model="columnSearchKeyword" placeholder="搜索列名"  style="margin-bottom: 8px;" clearable/>
                      </div>
                      <el-checkbox
                        v-model="isAllColumnsSelected"
                        :indeterminate="isIndeterminate"
                        @change="handleAllColumnsChange"
                        style="display: block; text-align: left; margin-left: 8px;"
                      >
                        全选
                      </el-checkbox>
                      <el-checkbox-group v-model="selectedColumnKeys">
                        <el-checkbox
                          v-for="col in filteredColumns"
                          :key="col.prop"
                          :label="col.prop"
                          :value="col.prop"
                          @change="(isChecked) => handleColumnChange(col,isChecked)"
                          style="display: block; text-align: left; margin-left: 8px;"
                        >
                          {{ col.label }}
                        </el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-popover>
                  <el-popover
                    ref="exportPopoverRef"
                    :virtual-ref="exportButtonRef"
                    trigger="click"
                    title="导出数据"
                    virtual-triggering
                    placement="bottom"
                    :width="180" 
                  >
                    <div>
                       <el-radio-group v-model="exportColumnsMode">
                        <el-radio-button label="可视列" value="visiable" />
                        <el-radio-button label="全部列" value="all" />
                      </el-radio-group>
                      <p/>
                      <el-radio-group v-model="exportDataMode">
                        <el-radio-button label="当前页" value="currentPage" />
                        <el-radio-button label="已选择" value="selected" />
                      </el-radio-group>
                      
                      <el-divider/>
                      <el-button :icon="Download" @click="handleExport">导出</el-button>
                    </div>                    
                  </el-popover>
                 <!-- <el-button v-if="props.selectionType==='multiple'" @click="toggleCheckStrictly " title="父子选择关联"><el-icon><Finished /></el-icon></el-button> -->                    
                </el-button-group>
              </template>
            </el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
    
    <!-- 高级搜索表单（折叠） -->
    <el-collapse v-if="searchColumns.length > 0 && advancedSearchVisible===true" v-model="activeSearchPanel">
      <el-collapse-item name="advanced">
        <template #title>
         <span style="font-size: 16px; font-weight: bold;">高级搜索</span>
        </template>
        <el-form ref="searchForm" :model="searchFields" label-width="auto" inline class="table-search-form">
          <el-form-item v-for="col in searchColumns" :key="col.prop" :label="col.label">
            <!-- 输入组件 -->
            <SearchInputs :col="col" :search-fields="searchFields" />
          </el-form-item>

          <!-- 按钮组统一放入 el-form-item -->
          <el-form-item label-width="0">
            <!-- <el-button @click="handleSearch">搜索</el-button> -->
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>
    </el-collapse>
  
  <el-table
    ref = "tableRef"
    v-bind="localTableOptions.options"
    :data="localTableData"
    :loading="loading"
    style="width: 100%"
    :show-summary="localTableOptions.showSummary"
    :summary-method="localTableOptions.summaryMethod" 
    :row-key="localTableOptions.rowKey"
    :tree-props="localTableOptions.treeProps"
    :span-method="localTableOptions.customRowColSpan"
    :table-layout="localTableOptions.tableLayout"
    :highlight-current-row="localTableOptions.selectionType === 'single'"
    @sort-change="handleSortChange"
    @selection-change="handleSelectionChange"
    @row-click="handleRowClick"
  >
    <el-table-column
      v-if="localTableOptions.selectionType === 'multiple'"
      type="selection"
      width="56"
    />
    <el-table-column
      v-else-if="localTableOptions.selectionType === 'single'"
      type="radio"
      width="56"
      label=""
    >
  <template #default="{ row }">
      <el-radio
        v-model="currentRowRadio"
        :value="row[localTableOptions.rowKey]"
      />
  </template>
</el-table-column>
    <template v-for="col in visibleColumns" :key="col.prop">
      <!-- 处理普通列 -->
      <el-table-column
        v-if="col.type !== 'action' && !col.children"
        :key="col.prop"
        :label="col.label"
        :width="col.width"
        :fixed="col.fixed"
        v-bind="col"
        :sortable="col.sortable || false"
        :sort-by="col.sortBy || col.prop"
        :align="col.align || 'left'"
        :header-align="col.headerAlign || col.align || 'left'"
        :resizable="col.resizable || true"
      >
      <template #default="scope">
        <!-- 如果存在 formatter，则使用 -->
        <span v-if="col.formatterFn && col.formatter">
          {{ col.formatter(scope.row, scope.column, scope.row[col.prop], scope.$index) }}
        </span>
        <!-- 否则直接显示原始值 -->
        <span v-else>{{ scope.row[col.prop] }}</span>
      </template>
      </el-table-column>

      <!-- 多级表头：递归处理子列 -->
      <el-table-column
        v-else-if="col.children"
        :key="col.prop || 'group'"
        :label="col.label"
        :width="col.width"
        :fixed="col.fixed"
        :align="col.align || 'left'"
        :header-align="col.headerAlign || col.align || 'left'"
        :resizable="col.resizable || true"
      >
        <template v-for="chdCol in col.children" :key="chdCol.prop">
          <el-table-column
            v-bind="chdCol"
            :sortable="chdCol.sortable || false"
            :sort-by="chdCol.sortBy || chdCol.prop"
            :align="chdCol.align || col.align || 'left'"
            :header-align="chdCol.headerAlign || col.headerAlign || chdCol.align || col.align || 'left'"
            :resizable="chdCol.resizable || true"
          >
            <template #default="scope">
              <!-- 如果存在 formatter，则使用 -->
              <span v-if="col.formatterFn && col.formatter">
                {{ col.formatter(scope.row, scope.column, scope.row[col.prop], scope.$index) }}
              </span>
              <!-- 否则直接显示原始值 -->
              <span v-else>{{ scope.row[col.prop] }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table-column>

      <!-- 动作列保持不变 -->
      <el-table-column
        v-else
        :key="'action'"
        :label="col.label"
        :fixed="getFixedValue(col)"
        :align="col.align || 'left'"
        :header-align="col.headerAlign || col.align || 'left'"
      >
        <template #default="scope">
          <slot name="action" :row="scope.row" :$index="scope.$index" />
        </template>
      </el-table-column>
    </template>
  </el-table>
  <el-pagination
    v-if="localTableOptions.pagination"
    style="margin-top: 16px; text-align: right"
    background
    layout="total, prev, pager, next, sizes, jumper"
    :total="total"
    :page-size="pageSize"
    :page-sizes="localTableOptions.options.pageSizes"
    :current-page="currentPage"
    @current-change="handlePageChange"
    @size-change="handleSizeChange"
  />

  <import-excel-dialog
    :importColumns="importColumns"
    ref="importExcelDialogRef"
    @submitImport="handleRealImport" />
  </div>
</template>

<script setup>
import { ref,unref, onMounted, watch, defineExpose,computed,nextTick } from 'vue'
import axios from 'axios'
import { ClickOutside as vClickOutside } from 'element-plus'
import { Plus,Search,Filter,Grid,Refresh,Download,Upload } from '@element-plus/icons-vue'
import SearchInputs from '@/components/search-inputs.vue'
import importExcelDialog from '@/components/import-excel-dialog.vue'
import {exportToExcel} from '@/utils/export'
import { getExcelImportData } from '@/utils/import'
import {deepClone, processIfProxy, isProxy, isEmpty} from '@/utils/utils'

const emit = defineEmits([
    'update:selected', 
    'update:current', 
    'sort-change',
    'update:tableColumns',
    'update:tableData',
    'update:tableOptions',
    'handleAdd'
  ])

const props = defineProps({
   tableOptions: { 
    type: Object, 
    default: () => ({
      dataApi: '', //http://localhost:5173/public/mockData.json
      rowKey: 'name',
      pagination: true,
      showSummary: true,
      summaryColumns: ['salary'],
      selectionType: 'multiple',
      selectedRowKeys: ['用户1','用户3'],
      options: { border: true, stripe: true, pageSizes: undefined },
      treeProps:{ 
        children: 'children', // 子级字段名
        hasChildren: 'hasChildren', // 是否有子级字段名（可选）
        checkStrictly: false, // 是否父子不关联
      },
      tableLayout:'fixed',
      showDefaultAdd: true,
      showAdvancedSearch: true,
      showRefresh: true,
      showColumns:true,
      showExport: true,
      showImport: true,
    }) 
  },
  tableColumns: { 
    type: Array,
    required: true, 
    default: () => []
  },
  tableData: { type: Array, default: () => [] }
})

/*
:row-span-method="(params) => {
    if (params.column.property === 'name') {
      if (params.rowIndex % 2 === 0) return 2
      else return 0
    }
    return 1
  }"
 */
const localTableColumns = ref(props.tableColumns) //  表格列数据
const localTableOptions = ref(props.tableOptions) //  表格配置
const localTableData = ref(props.tableData) //  表格数据

const loading = ref(false)  //  表格加载状态
const total = ref(0)     //  表格数据总数
const currentPage = ref(1)  //  当前页码
const pageSize = ref(10)    //  当前页大小
const sortProp = ref('')    //  排序字段
const sortOrder = ref('')  //  排序方式  
const selectedRows = ref([])  //  选中行
const currentRow = ref(null)  //  当前行
const tableRef = ref()

//const searchKeyword = ref('') //  搜索关键字
// 不用computed,手动调用减少执行
const getVisibleColumns = () =>{
  return [...localTableColumns.value].filter(col => col.visible !== false)
    .map(col => {
        if (typeof col.formatterFn === 'string' && col.formatterFn) {
          const fn = parseFormatter(col.formatterFn)
          //console.log(fn)
          if (fn) {
            return { ...col, formatter: fn }
          }
        }
        return col
      })
}

 
const visibleColumns = ref(getVisibleColumns())

const refreshVisibleColumns=()=>{
  //selectedColumnKeys.value=[]
  visibleColumns.value = getVisibleColumns()

    nextTick(()=>{
      selectedColumnKeys.value= [...visibleColumns.value].map(col => col.prop)         
    })
          
}

// const columnSettingDropdown  = ref()

// 搜索条件对象
const searchFields = ref({})

const columnSearchKeyword = ref('') // 列名搜索关键词
// 直接使用 visibleColumns
const selectedColumnKeys = ref(
    visibleColumns.value
   // .filter(col => col.visible !== false)
    .map(col => col.prop)
)
const isAllColumnsSelected = ref(true)
const isIndeterminate = ref(false)

const advancedSearchVisible = ref(false)
const activeSearchPanel = ref([]) // 控制 collapse 展开状态
const generalSearchKeyword = ref('') // 通用搜索关键词

const buttonRef = ref()
const popoverRef = ref()
const exportButtonRef = ref()
const exportPopoverRef = ref()
const exportColumnsMode = ref('visiable')
const exportDataMode = ref('currentPage')
const onClickOutside = () => {
  unref(popoverRef).popperRef?.delayHide?.()
}
const onClickOutsideExport = () => {
  unref(exportPopoverRef).exportButtonRef?.delayHide?.()
}

const currentRowRadio = computed({
  get: () => currentRow.value ? currentRow.value[localTableOptions.value.rowKey] : null,
  set: (key) => {
    const row = localTableData.value.find(r => r[localTableOptions.value.rowKey] === key)
    if (row) {
      currentRow.value = row
      selectedRows.value = [row]
      emit('update:current', row)
    }
  }
})

function parseFormatter(str) {
  if(!str) return null  
  try {
    // 使用 new Function 构建 formatter 函数
    return new Function('row', 'column', 'cellValue', 'index', str)
  } catch (e) {
    console.error('formatter 解析失败:', e)
    return null
  }
}
// 方法：设置可见列
function setVisibleColumns(propsArray) {
  visibleColumns.value = localTableColumns.value.filter(col => propsArray.includes(col.prop || col.type))
}

function getFixedValue(col) {
  return typeof col.fixed === 'string' && ['left', 'right'].includes(col.fixed)
    ? col.fixed
    : 'right'
}
function getSelectionRows() {
  return selectedRows.value
}

function getSelectionRowKeys() {
  return selectedRows.value.map(col => col[localTableOptions.value.rowKey])
}

function clearSelection(){
  tableRef.value?.clearSelection()
}

function toggleAllSelection(){
  tableRef.value?.toggleAllSelection()
}

function toggleRowSelection(row, selected) {
  tableRef.value?.toggleRowSelection(row, selected)
}

// 过滤出需要搜索的列
const searchColumns = computed(() => {
  return localTableColumns.value.filter(col => col.searchable)
})

const toggleAdvancedSearch = () => {
  advancedSearchVisible.value = !advancedSearchVisible.value
  if (advancedSearchVisible.value) {
    activeSearchPanel.value = ['advanced']
  } else {
    activeSearchPanel.value = []
  }
}

const toggleCheckStrictly=() => {
  localTableOptions.value.treeProps.checkStrictly = !localTableOptions.value.treeProps.checkStrictly 
}
// 处理通用搜索
const handleGeneralSearch = () => {
  currentPage.value = 1
  searchFields.value['search'] = generalSearchKeyword.value
  fetchData()
}
// 处理高级搜索
const handleSearch = () => {
  currentPage.value = 1
  searchFields.value['search'] = generalSearchKeyword.value
  fetchData()
}
// 重置搜索
const resetSearch = () => {
  for (const key in searchFields.value) {
    searchFields.value[key] = ''
  }
  generalSearchKeyword.value = ''
  currentPage.value = 1
  fetchData()
}
// 新增操作
const onAdd = () => {
  emit('handleAdd') // 可选：暴露 add 事件给父组件
}
const filterLocalData = (data, searchFields, keyword) => {
  return data.filter(row => {
    // 先检查通用搜索关键词
     const generalMatch = !keyword ? false : Object.values(row).some(val =>
          String(val).toLowerCase().includes(keyword.toLowerCase())
        );


    // 再检查高级搜索字段匹配
    const advancedMatch = Object.entries(searchFields).every(([key, value]) => {
      if (!value) return true; // 如果搜索值为空，则忽略该字段
      return String(row[key]).toLowerCase().includes(String(value).toLowerCase());
    });

    return generalMatch || advancedMatch;
  });
};

const fetchData = async () => {
  loading.value = true;
  try {
    if (!localTableOptions.value.dataApi && localTableData.value) { // 如果没有数据接口，则使用本地数据
      let localData = localTableData.value;
      //console.log('localData:', searchFields.value)
      // 处理本地数据结构
      if (Array.isArray(localData)) {
        // 纯数组数据
        localTableData.value = filterLocalData(localData, searchFields.value, generalSearchKeyword.value);
        total.value = localTableData.value.length;
      } else if (localData.data && Array.isArray(localData.data)) {
        // 分页结构对象
        const filtered = filterLocalData(localData.data, searchFields.value, generalSearchKeyword.value);
        total.value = filtered.length;

        if (localTableOptions.value.pagination) {
          const start = (currentPage.value - 1) * pageSize.value;
          const end = start + pageSize.value;
          localTableData.value = filtered.slice(start, end);
        } else {
          localTableData.value = filtered;
        }
      } else {
        console.warn('Invalid data format passed to <g-table :data="...">');
        localTableData.value = [];
        total.value = 0;
      }
    } else { //远程数据源
      const params = {
        ...(localTableOptions.value.pagination ? { page: currentPage.value, pageSize: pageSize.value } : {}),
        ...(sortProp.value ? { sort: sortProp.value, order: sortOrder.value } : {}),
        ...searchFields.value
      };
      const res = await axios.post(localTableOptions.value.dataApi, { params });

      if (localTableOptions.value.dataApi.endsWith('.json')) {
        const allData = res.data.data || res.data;
        const filtered = filterLocalData(allData, searchFields.value, generalSearchKeyword.value);
        total.value = res.data.total || allData.length;

        if (localTableOptions.value.pagination) {
          const start = (currentPage.value - 1) * pageSize.value;
          const end = start + pageSize.value;
          localTableData.value = filtered.slice(start, end);
        } else {
          localTableData.value = filtered;
        }
      } else { // 后台处理检索
        localTableData.value = res.data.data || res.data;
        if (localTableOptions.value.pagination) {
          total.value = res.data.total || 0;
        }
      }
    }
  } finally {
    loading.value = false;
  }
}

const customRowColSpan = (params) => {
  const { row, column, rowIndex, columnIndex } = params

  // 先尝试使用用户定义的行合并逻辑
  if (localTableOptions.value.rowSpanMethod && column.type !== 'selection' && column.type !== 'radio') {
    const span = localTableOptions.value.rowSpanMethod(params)
    if (span !== undefined) {
      return { rowspan: span, colspan: 1 }
    }
  }

  // 再尝试使用用户定义的列合并逻辑
  if (localTableOptions.value.colSpanMethod) {
    const span = localTableOptions.value.colSpanMethod(params)
    if (span !== undefined) {
      return { rowspan: 1, colspan: span }
    }
  }

  // 默认不合并
  return { rowspan: 1, colspan: 1 }
}

const handlePageChange = (page) => {
  currentPage.value = page
  fetchData()
}
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchData()
}
const handleSortChange = ({ prop, order }) => {
  sortProp.value = prop
  sortOrder.value = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : ''
  emit('sort-change', { prop, order: sortOrder.value })
  fetchData()
}
const handleSelectionChange = (val) => {
  selectedRows.value = val
  emit('update:selected', val)
}
const handleRowClick = (row) => {
  if (localTableOptions.value.selectionType === 'single') {
    currentRow.value = row
    selectedRows.value = [row]
    emit('update:current', row)
  }
}

const summaryMethod = (params) => {
  const { columns, data } = params
  return columns.map((column, index) => {
    if (index === 0) return '合计'
    if (localTableOptions.value.summaryColumns.includes(column.property)) {
      return data.reduce((sum, row) => {
        const val = Number(row[column.property])
        return sum + (isNaN(val) ? 0 : val)
      }, 0)
    }
    return ''
  })
}

// 过滤后的列（根据搜索关键字）
const filteredColumns = computed(() => {
  return localTableColumns.value.filter(col =>col.label?.toLowerCase().includes(columnSearchKeyword.value.toLowerCase())
  )
})

// 全选切换
function handleAllColumnsChange(val) {
  if (val) {
    selectedColumnKeys.value = filteredColumns.value.map(col => col.prop)
    localTableColumns.value.filter(col => col.visible === false).map(col => col.visible = true);
  } else {
    selectedColumnKeys.value = []
    localTableColumns.value.filter(col => col.visible === true).map(col => col.visible = false);
  }
  updateVisibleColumnsList()
}

// 单个列切换
function handleColumnChange(column,isChecked) {  
  localTableColumns.value.filter(col => col.prop === column.prop).map(col => col.visible = isChecked);
  // 更新全选状态
  isAllColumnsSelected.value = selectedColumnKeys.value.length === filteredColumns.value.length
  isIndeterminate.value = selectedColumnKeys.value.length > 0 && selectedColumnKeys.value.length < filteredColumns.value.length
  updateVisibleColumnsList()
}

// 点击字段列表 更新 visibleColumns
function updateVisibleColumnsList() { 
  visibleColumns.value = localTableColumns.value
    .filter(col => selectedColumnKeys.value.includes(col.prop))
}
const setSelectedRows = () => {
  if (localTableOptions.value.selectedRowKeys?.length > 0) {
      localTableData.value.forEach(row => {
        if (localTableOptions.value.selectedRowKeys.includes(row[localTableOptions.value.rowKey])) {
          toggleRowSelection(row, true)
        }
      })
    } 
}
const refreshTable = () => { 
  refreshVisibleColumns()
  fetchData()
  nextTick(() => {
    setSelectedRows();
  })
}


onMounted(async () => {
  // refreshTable()
  refreshVisibleColumns()
  await fetchData()
  await nextTick(() => {
    setSelectedRows();
  })
})

const prepareExportData = () => {
  let dataToExport = [];

  // 数据来源：当前页 or 已选中行
  if (exportDataMode.value === 'currentPage') {
    dataToExport = localTableData.value;
  } else if (exportDataMode.value === 'selected') {
    dataToExport = selectedRows.value;
  }

  // 列来源：可视列 or 所有列
  let columnsToExport = [];
  if (exportColumnsMode.value === 'visiable') {
    columnsToExport = visibleColumns.value;
  } else if (exportColumnsMode.value === 'all') {
    columnsToExport = localTableColumns.value;
  }

  // 过滤掉 action 类型的列
  columnsToExport = columnsToExport.filter(col => col.type !== 'action');

  // 提取字段名和对应表头
  const fields = columnsToExport.map(col => ({
    key: col.prop,
    title: col.label,
  }));

  // 构造带标题的二维数组
  const worksheetData = [fields.map(f => f.title)]; // 表头行
  dataToExport.forEach(row => {
    const rowData = fields.map(field => row[field.key]);
    worksheetData.push(rowData);
  });

  return worksheetData;
}

const handleExport=()=>{
  exportToExcel(prepareExportData())
}
/*
const handleExcelImport = async () => {
  try {
    const excelData = await getExcelImportData(); //
    console.log('解析后的数据:', excelData);
  } catch (error) {
    console.error('导入失败:', error);
  }
}*/
const importExcelDialogRef = ref()
const importColumns = [
   // { type: 'selection', width: 55, align: 'center' },
    ...localTableColumns.value.filter(item => item.type !== 'action').map(({ prop, label }) => ({ prop, label }))]
const handleRealImport=(data)=>{ 
  console.log('导入的数据:', data);
}

const handleExcelImport=()=>{
  
   getExcelImportData().then(data => {
      importExcelDialogRef.value.showPreview(data)
    }).catch(err => {
      console.error('导入失败:', err);
    });
}

const handleSubmit=(event)=> {
      event.preventDefault(); // 阻止表单提交
      handleGeneralSearch()
    }

const setSearchKeyword = (keyword) => {
  generalSearchKeyword.value = keyword
  handleGeneralSearch()
}
const setTableColumns = (columns) => {
  localTableColumns.value = columns
}
const setTableOptions = (options) => {
  localTableOptions.value = options
}
const setTableData = (data) => {
  localTableData.value = data
}

const getTableColumns = () => {
  return localTableColumns.value
}
const getTableOptions = () => {
  return localTableOptions.value
}
const getTableData = () => {
  return localTableData.value
}


watch([() => props.dataApi, currentPage, pageSize], fetchData)
watch(
  () => props.tableColumns, (newVal) => {
    localTableColumns.value=newVal
  },{ deep: true, immediate: true }
)
watch(
  () => props.tableData, (newVal) => {
    localTableData.value=newVal
  },{ deep: true, immediate: true }
)
watch(
  () => props.tableOptions, (newVal) => {
    localTableOptions.value=newVal
  },{ deep: true, immediate: true }
)
watch(
  () => localTableColumns, (newVal) => {
    emit('update:tableColumns',localTableColumns.value)
  },{ deep: true, immediate: true }
)
watch(
  () => localTableData, (newVal) => {
    emit('update:tableData',localTableData.value)
  },{ deep: true, immediate: true }
)
watch(
  () => localTableOptions, (newVal) => {
    emit('update:tableOptions', localTableOptions.value)
  },{ deep: true, immediate: true }
)

watch(generalSearchKeyword, (newVal) => {
  currentPage.value = 1
  searchFields.value['search'] = newVal
  fetchData()
})

//暴露方法可进行手动同步或调用
defineExpose({
	setTableColumns,
  setTableOptions,
	setTableData,
	getTableColumns,
  getTableOptions,
	getTableData,
  refreshTable,
  setSearchKeyword,
  setVisibleColumns,
  getSelectionRows,
  getSelectionRowKeys,
  getSelectionKeys: getSelectionRowKeys,
  clearSelection,
  toggleAllSelection,
  toggleRowSelection,
  toggleCheckStrictly,
  // utils 常用方法
  isEmpty: isEmpty,
  isProxy: isProxy,
  deepClone: deepClone,
  proxyToRaw: processIfProxy,
})

</script>


<style scoped> 
.toolbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}
.table-toolbar {
  flex: 1;
  min-width: max-content;
}
.table-search-toolbar {
  flex: 1;
  min-width: max-content;
  text-align: right;
  margin-top: 14px;
  margin-bottom: 0px;
  .el-form--inline .el-form-item{
    margin-right: 0px;
  }
  .search-button-group {
    .el-button, .el-button.is-round {
        padding: 8px 1px;
        width: 32px;
         background-color: #909399 !important; /* info 主色 */
        color: #fff !important;
    } 
  }
}

.search-and-select {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

</style> 